package algorithm.linkedList;

/**
 * 借助链表实现两数相加
 * 难度比较低
 */
public class SumTwoNumber {
    public static ListNode sumTwoNumber(ListNode h1,ListNode h2){
        ListNode ans=null;
        ListNode cur=null;
        int flag=0;
        while(h1!=null||h2!=null){
            int val1=h1==null?0:h1.val;
            int val2=h2==null?0:h2.val;
            int sum=val1+val2+flag;
            flag=sum/10;
            int val=sum%10;
            if(ans==null){
                ans=new ListNode(val);
                cur=ans;
            }else{
                cur.next=new ListNode(val);
                cur=cur.next;
            }
            h1=h1==null?null:h1.next;
            h2=h2==null?null:h2.next;
        }
        if(flag==1){
            cur.next=new ListNode(1);
        }
        return ans;
    }
}
